package com.jspxcms.core.web.fore;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jspxcms.common.util.JsonResponse;
import com.jspxcms.plug.domain.UserFavorite;
import com.jspxcms.plug.service.UserFavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jspxcms.common.security.CredentialsDigest;
import com.jspxcms.common.web.Validations;
import com.jspxcms.core.domain.Site;
import com.jspxcms.core.domain.User;
import com.jspxcms.core.domain.UserDetail;
import com.jspxcms.core.service.UserService;
import com.jspxcms.core.support.Context;
import com.jspxcms.core.support.ForeContext;
import com.jspxcms.core.support.Response;

/**
 * MemberController
 *
 * @author liufang
 */
@Controller
public class MemberController {
    public static final String SPACE_TEMPLATE = "sys_member_space.html";
    public static final String MY_TEMPLATE = "sys_member_my.html";
    public static final String PROFILE_TEMPLATE = "sys_member_profile.html";
    public static final String PASSWORD_TEMPLATE = "sys_member_password.html";
    public static final String EMAIL_TEMPLATE = "sys_member_email.html";

    /**
     * 会员首页
     *
     * @param request
     * @param response
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/space/{id}.jspx")
    public String space(@PathVariable Integer id, HttpServletRequest request,
                        HttpServletResponse response, org.springframework.ui.Model modelMap) {
        Response resp = new Response(request, response, modelMap);
        List<String> messages = resp.getMessages();
        User targetUser = userService.get(id);
        if (!Validations.exist(targetUser, messages, "User", id)) {
            return resp.notFound();
        }

        Site site = Context.getCurrentSite(request);
        modelMap.addAttribute("targetUser", targetUser);
        Map<String, Object> data = modelMap.asMap();
        ForeContext.setData(data, request);
        return site.getTemplate(SPACE_TEMPLATE);
    }

    @RequestMapping(value = "/my.jspx")
    public String my(HttpServletRequest request, HttpServletResponse response,
                     org.springframework.ui.Model modelMap) {
        Site site = Context.getCurrentSite(request);
        Map<String, Object> data = modelMap.asMap();
        ForeContext.setData(data, request);

        //Response resp = new Response(request, response, modelMap);
        User user = Context.getCurrentUser(request);
        data.put("user", user);
        //user.setGender(gender);
        //user.setBirthDate(birthDate);
        UserDetail detail = user.getDetail();
        data.put("userDetail", detail);

        Page<UserFavorite> byUserIdFavorite = favoriteService.findByUserId(user.getId(), 1, 0, 5);
        data.put("favorites", byUserIdFavorite.getContent());

        Page<UserFavorite> byUserIdStudy = favoriteService.findByUserId(user.getId(), 2, 0, 5);
        data.put("studies", byUserIdStudy.getContent());

        return site.getTemplate(MY_TEMPLATE);
    }


    @RequestMapping(value = "/my_favorite.jspx")
    public String myFavorite(
            Integer page,
            HttpServletRequest request,
            HttpServletResponse response,
            org.springframework.ui.Model modelMap) {
        Site site = Context.getCurrentSite(request);
        Map<String, Object> data = modelMap.asMap();
        ForeContext.setData(data, request);

        User user = Context.getCurrentUser(request);
        data.put("user", user);

        UserDetail detail = user.getDetail();
        data.put("userDetail", detail);
        if (page == null || page < 1) {
            page = 1;
        }
        Page<UserFavorite> byUserId = favoriteService.findByUserId(user.getId(), 1, page - 1, 10);
        data.put("pagedList", byUserId);
        data.put("page", page);
        data.put("url", "/my_favorite.jspx");

        return site.getTemplate("sys_member_my_favorite.html");
    }

    @RequestMapping(value = "/my_goods.jspx")
    public String myGoods(
            Integer page,
            HttpServletRequest request,
            HttpServletResponse response,
            org.springframework.ui.Model modelMap) {
        Site site = Context.getCurrentSite(request);
        Map<String, Object> data = modelMap.asMap();
        ForeContext.setData(data, request);

        User user = Context.getCurrentUser(request);
        data.put("user", user);

        if (user != null) {
            UserDetail detail = user.getDetail();
            data.put("userDetail", detail);
        }

        data.put("page", page == null ? 1 : page);
        return site.getTemplate("sys_member_my_goods.html");
    }

    @RequestMapping(value = "/my_study.jspx")
    public String myStudy(
            Integer page,
            HttpServletRequest request,
            HttpServletResponse response,
            org.springframework.ui.Model modelMap) {
        Site site = Context.getCurrentSite(request);
        Map<String, Object> data = modelMap.asMap();
        ForeContext.setData(data, request);

        User user = Context.getCurrentUser(request);
        data.put("user", user);

        UserDetail detail = user.getDetail();
        data.put("userDetail", detail);

        if (page == null || page < 1) {
            page = 1;
        }
        Page<UserFavorite> byUserId = favoriteService.findByUserId(user.getId(), 1, page - 1, 10);
        data.put("pagedList", byUserId);
        data.put("page", page);
        data.put("url", "/my_study.jspx");
        return site.getTemplate("sys_member_my_study.html");
    }


    @RequestMapping(value = "/my/profile.jspx")
    public String profileForm(HttpServletRequest request,
                              HttpServletResponse response, org.springframework.ui.Model modelMap) {
        Site site = Context.getCurrentSite(request);
        Map<String, Object> data = modelMap.asMap();
        ForeContext.setData(data, request);

        //Response resp = new Response(request, response, modelMap);
        User user = Context.getCurrentUser(request);
        data.put("user", user);
        UserDetail detail = user.getDetail();
        data.put("userDetail", detail);


        return site.getTemplate(PROFILE_TEMPLATE);
    }

    @RequestMapping(value = "/my/profile.jspx", method = RequestMethod.POST)
    public Object profileSubmit(Integer userId, String logo, String nickname, String password, String password_repeate, String hospital,
                                HttpServletRequest request,
                                HttpServletResponse response,
                                org.springframework.ui.Model modelMap) {
        Response resp = new Response(request, response, modelMap);
        if (password != null && password_repeate != null) {
            if (!password.equals(password_repeate)) {
                return JsonResponse.jsonOutput(response, -1, "两次密码不同,请重新验证");
            }
        }
        try {
            userService.update(userId, logo, nickname, password, hospital);
            return JsonResponse.jsonOutput(response, 1, "更新成功");
        } catch (Exception ex) {
            ex.printStackTrace();
            return JsonResponse.jsonOutput(response, -1, "更新失败");
        }
    }

    @RequestMapping(value = "/my/password.jspx")
    public String passwordForm(HttpServletRequest request,
                               HttpServletResponse response, org.springframework.ui.Model modelMap) {
        Site site = Context.getCurrentSite(request);
        Map<String, Object> data = modelMap.asMap();
        ForeContext.setData(data, request);
        return site.getTemplate(PASSWORD_TEMPLATE);
    }

    @RequestMapping(value = "/my/password.jspx", method = RequestMethod.POST)
    public String passwordSubmit(String password, String rawPassword,
                                 HttpServletRequest request, HttpServletResponse response,
                                 org.springframework.ui.Model modelMap) {
        Response resp = new Response(request, response, modelMap);
        User user = Context.getCurrentUser(request);
        if (!credentialsDigest.matches(user.getPassword(), password,
                user.getSaltBytes())) {
            return resp.post(501, "member.passwordError");
        }
        userService.updatePassword(user.getId(), rawPassword);
        return resp.post();
    }

    @RequestMapping(value = "/my/email.jspx")
    public String emailForm(HttpServletRequest request,
                            HttpServletResponse response, org.springframework.ui.Model modelMap) {
        Site site = Context.getCurrentSite(request);
        Map<String, Object> data = modelMap.asMap();
        ForeContext.setData(data, request);
        return site.getTemplate(EMAIL_TEMPLATE);
    }

    /**
     * 修改邮箱
     *
     * @param request
     * @param response
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/my/email.jspx", method = RequestMethod.POST)
    public String emailSubmit(String password, String email,
                              HttpServletRequest request, HttpServletResponse response,
                              org.springframework.ui.Model modelMap) {
        // TODO 修改邮箱后需重新激活才能生效
        Response resp = new Response(request, response, modelMap);
        List<String> messages = resp.getMessages();
        if (!Validations.notEmpty(email, messages, "email")) {
            return resp.post(401);
        }
        if (!Validations.email(email, messages, "email")) {
            return resp.post(402);
        }
        User user = Context.getCurrentUser(request);
        if (!credentialsDigest.matches(user.getPassword(), password,
                user.getSaltBytes())) {
            return resp.post(501, "member.passwordError");
        }
        userService.updateEmail(user.getId(), email);
        return resp.post();
    }

    @Autowired
    private CredentialsDigest credentialsDigest;
    @Autowired
    private UserService userService;
    @Autowired
    private UserFavoriteService favoriteService;
}
